package com.keba.lamp.complaint.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.keba.basic.annotation.log.WebLog;
import com.keba.basic.base.R;
import com.keba.basic.base.request.PageParams;
import com.keba.basic.database.mybatis.conditions.Wraps;
import com.keba.basic.interfaces.echo.EchoService;
import com.keba.basic.utils.BeanPlusUtil;
import com.keba.lamp.complaint.entity.DocTemplateArea;
import com.keba.lamp.complaint.service.DocTemplateAreaService;
import com.keba.lamp.complaint.vo.result.DocTemplateAreaResultVO;
import com.keba.lamp.complaint.vo.result.DocTemplateUserResultVO;
import com.keba.lamp.office.properties.WebOfficeProperties;
import com.keba.lamp.office.service.OfficeApiFacade;
import com.keba.lamp.office.vo.OfficeInitVO;
import com.keba.lamp.office.vo.OfficeQueryVO;
import com.keba.lamp.system.entity.system.DefArea;
import com.keba.lamp.system.service.system.DefAreaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.keba.basic.base.controller.SuperController;
import com.keba.lamp.complaint.service.DocTemplateService;
import com.keba.lamp.complaint.entity.DocTemplate;
import com.keba.lamp.complaint.vo.save.DocTemplateSaveVO;
import com.keba.lamp.complaint.vo.update.DocTemplateUpdateVO;
import com.keba.lamp.complaint.vo.result.DocTemplateResultVO;
import com.keba.lamp.complaint.vo.query.DocTemplatePageQuery;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * 文书模版
 * </p>
 *
 * @author twg
 * @date 2025-07-09 15:45:42
 * @create [2025-07-09 15:45:42] [twg] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/docTemplate")
@Tag(name = "文书模版")
public class DocTemplateController extends SuperController<DocTemplateService, Long, DocTemplate, DocTemplateSaveVO, DocTemplateUpdateVO, DocTemplatePageQuery, DocTemplateResultVO> {
    private final EchoService echoService;

    private final OfficeApiFacade officeApiFacade;

    private final DocTemplateAreaService docTemplateAreaService;


    private final DefAreaService defAreaService;

    private final WebOfficeProperties webOfficeProperties;

    @Override
    public EchoService getEchoService() {
        return echoService;
    }


    @Override
    public R<IPage<DocTemplateResultVO>> page(PageParams<DocTemplatePageQuery> params) {
        List<DocTemplateArea> docTemplateAreas = docTemplateAreaService.list(Wraps.<DocTemplateArea>lbQ().select(DocTemplateArea::getDocTemplateId, DocTemplateArea::getAreaId)
                .in(CollUtil.isNotEmpty(params.getModel().getAreaIds()), DocTemplateArea::getAreaId, params.getModel().getAreaIds()));
        List<Long> docTemplateIds = docTemplateAreas.stream().map(DocTemplateArea::getDocTemplateId).collect(Collectors.toList());
        if (CollUtil.isEmpty(docTemplateIds)) {
            return R.success(params.buildPage());
        }
        List<Long> areaIds = docTemplateAreas.stream().map(DocTemplateArea::getAreaId).collect(Collectors.toList());
        Map<Long, String> areaMap = defAreaService.listByIds(areaIds).stream().collect(Collectors.toMap(DefArea::getId, DefArea::getName));
        List<DocTemplateAreaResultVO> docTemplateAreaResults = BeanPlusUtil.toBeanList(docTemplateAreas, DocTemplateAreaResultVO.class);
        docTemplateAreaResults.forEach(docTemplateArea -> docTemplateArea.setAreaName(areaMap.getOrDefault(docTemplateArea.getAreaId(), "")));
        Map<Long, List<DocTemplateAreaResultVO>> docMap = docTemplateAreaResults.stream().collect(Collectors.groupingBy(DocTemplateAreaResultVO::getDocTemplateId));

        params.getExtra().put("id_in", docTemplateIds);
        IPage<DocTemplate> page = query(params);
        IPage<DocTemplateResultVO> voPage = BeanPlusUtil.toBeanPage(page, getResultVOClass());
        handlerResult(voPage);
        voPage.getRecords().forEach(o -> {
            List<DocTemplateAreaResultVO> list = docMap.getOrDefault(o.getId(), new ArrayList<>()).stream().filter(a -> StrUtil.isNotBlank(a.getAreaName())).collect(Collectors.toList());
            o.setAppId(webOfficeProperties.getAppId())
                    .setAreaIds(list.stream().map(DocTemplateAreaResultVO::getAreaId).collect(Collectors.toList()))
                    .setAreaName(String.join(",", list.stream().map(DocTemplateAreaResultVO::getAreaName).collect(Collectors.joining(","))));
        });
        return success(voPage);
    }

    /**
     * 文书模板填充值
     *
     * @return
     */
    @Operation(summary = "获取文书模板填充值")
    @GetMapping("/getDocTemplateValue")
    public R<DocTemplateUserResultVO> getDocTemplateValue(@RequestParam Long docId) {
        return R.success(superService.getDocTemplateValue(docId));
    }

    /**
     * 初始化
     *
     * @return
     */
    @Operation(summary = "标准模版初始化")
    @PostMapping("/init")
    @WebLog("标准模版初始化")
    public R<OfficeInitVO> init(@RequestBody @Validated OfficeQueryVO queryVO) {
        return R.success(officeApiFacade.initOffice(queryVO));
    }





}


